const app = getApp();
const { post, upload } = require('../../utils/request');

Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    phone: '',
    avatarUrl: '',
    gender: '',
    height: '',
    weight: '',
    age: '',
    goalIndex: null,
    goals: ['减重', '增肌', '保持健康'],
    dietaryOptions: [
      { label: '无糖', value: 'sugar-free', checked: false },
      { label: '无麸质', value: 'gluten-free', checked: false },
      { label: '素食', value: 'vegetarian', checked: false },
      { label: '低脂', value: 'low-fat', checked: false },
      { label: '低碳水', value: 'low-carb', checked: false }
    ],
    dietaryRestrictions: [],
    isAgreed: false,
    isFormValid: false
  },

  onUsernameInput(e) {
    this.setData({ username: e.detail.value });
    this.validateForm();
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
    this.validateForm();
  },

  onConfirmPasswordInput(e) {
    this.setData({ confirmPassword: e.detail.value });
    this.validateForm();
  },

  onNicknameInput(e) {
    this.setData({ nickname: e.detail.value });
  },

  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
    this.validateForm();
  },

  onGenderChange(e) {
    this.setData({ gender: e.detail.value });
  },

  onHeightInput(e) {
    this.setData({ height: e.detail.value });
  },

  onWeightInput(e) {
    this.setData({ weight: e.detail.value });
  },

  onAgeInput(e) {
    this.setData({ age: e.detail.value });
  },

  onGoalChange(e) {
    this.setData({ goalIndex: e.detail.value });
  },

  onDietaryRestrictionsChange(e) {
    const values = e.detail.value;
    const options = this.data.dietaryOptions.map(option => ({
      ...option,
      checked: values.includes(option.value)
    }));
    
    this.setData({
      dietaryOptions: options,
      dietaryRestrictions: values
    });
  },

  async chooseAvatar() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });

      const tempFilePath = res.tempFilePaths[0];
      
      wx.showLoading({
        title: '上传中...'
      });

      const uploadResult = await upload('/upload/avatar', tempFilePath, 'avatar');
      
      wx.hideLoading();
      
      this.setData({
        avatarUrl: uploadResult.url
      });
      
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '上传失败',
        icon: 'none'
      });
    }
  },

  validateForm() {
    const { username, password, confirmPassword, phone } = this.data;
    
    const isUsernameValid = username.length >= 3;
    
    const isPasswordValid = password.length >= 6;
    
    const isConfirmPasswordValid = password === confirmPassword;
    
    const isPhoneValid = /^1\d{10}$/.test(phone);
    
    const isFormValid = isUsernameValid && 
                       isPasswordValid && 
                       isConfirmPasswordValid && 
                       isPhoneValid;

    this.setData({ isFormValid });
  },

  onAgreementChange(e) {
    this.setData({
      isAgreed: e.detail.value.length > 0
    });
  },

  viewAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/index'
    });
  },

  async handleRegister() {
    if (!this.data.isFormValid || !this.data.isAgreed) return;

    const { 
      username, 
      password, 
      nickname,
      phone,
      avatarUrl,
      gender,
      height,
      weight,
      age,
      goalIndex,
      dietaryRestrictions
    } = this.data;

    try {
      wx.showLoading({
        title: '注册中...'
      });

      const res = await post('/users/register', {
        username,
        password,
        nickname: nickname || username,
        phone,
        avatar: avatarUrl,
        gender,
        height: parseFloat(height) || null,
        weight: parseFloat(weight) || null,
        age: parseInt(age) || null,
        goal: goalIndex !== null ? this.data.goals[goalIndex] : null,
        dietaryRestrictions
      });

      wx.hideLoading();

      if (res.token) {
        wx.setStorageSync('token', res.token);
        wx.setStorageSync('userInfo',res.user)
        app.globalData.userInfo = res.user;
        app.globalData.hasLogin = true;

        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });

        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      } else {
        throw new Error('注册失败');
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '注册失败',
        icon: 'none'
      });
    }
  },

  navigateToLogin() {
    wx.navigateBack();
  }
}); 